package com.yzs.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzs.common.bean.R;
import com.yzs.entity.House;
import com.yzs.entity.Order;
import com.yzs.entity.PageResult;
import com.yzs.mapper.AdminMapper;
import com.yzs.mapper.HouseMapper;
import com.yzs.mapper.OrderMapper;
import com.yzs.service.IHouseService;
import com.yzs.utils.JwtUtil;
import com.yzs.utils.ModelUtil;
import com.yzs.utils.TimeUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class HouseServiceImpl implements IHouseService {
    @Autowired
    HouseMapper mapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    JwtUtil JwtUtil;
    private final String ALI_OSS_URL = "https://home-y.oss-cn-hangzhou.aliyuncs.com/";
    private final String endPoint = "http://oss-cn-hangzhou.aliyuncs.com/";
    private final String accessKeyId = "LTAI5t7S3b7tQjxFUnYa2x1c";
    private final String accessKeySecret = "cp7jZPh44Fh7rZUT0yFOeMVbTHVUbj";
    private final String bucketName = "home-y";
    private final String ossFileName = "houseImg/";


    @Override
    public R getHouseByPage(Integer currentPage, Integer pageSize) {
        Page<House> page = new Page<>(currentPage, pageSize);
        QueryWrapper<House> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("id");
        page = mapper.selectPage(page, wrapper);
        if (page.getRecords().isEmpty()) {
            return R.error("no data！");
        } else {
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            for (House house : page.getRecords()) {
                List<OSSObjectSummary> houseImgList = ossClient.listObjects(bucketName, ossFileName + house.getImgFile()).getObjectSummaries();
                String[] imgS = new String[houseImgList.size()];
                for (int j = 0; j < imgS.length; j++) {
                    imgS[j] = houseImgList.get(j).getKey();
                }
                house.setImgFileNames(imgS);
            }
            ossClient.shutdown();
        }
        PageResult<House> data = new PageResult<>(page.getTotal(), page.getRecords());
        return R.ok(data);
    }

    @Override
    public R getHouseById(String id) {
        House house = mapper.selectById(id);
        if (house != null) {
            // 如果图片目录没有创建自动生成
            if (house.getImgFile() == null) {
                house.setImgFile(System.currentTimeMillis() + "_" + house.getId());
                int i = mapper.updateById(house);
                if (i != 1) {
                    return R.error("服务器开小差！请重试！");
                }
            }
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            List<OSSObjectSummary> houseImgList = ossClient.listObjects(bucketName, ossFileName + house.getImgFile()).getObjectSummaries();
            String[] imgS = new String[houseImgList.size()];
            for (int j = 0; j < imgS.length; j++) {
                imgS[j] = houseImgList.get(j).getKey();
            }
            house.setImgFileNames(imgS);
            ossClient.shutdown();
            return R.ok(house);
        }
        return R.error("房源出错！");
    }

    @Override
    public R uploadPicture(MultipartFile[] files, String token, String houseId) {
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        for (MultipartFile file : files) {
            House house = mapper.selectById(houseId);
            String imgFile = house.getImgFile();
            int fileLength = 0;
            // 图片未上传 创建文件夹并将文件夹名写入数据库
            List<OSSObjectSummary> ossHouseImgList = ossClient.listObjects("home-y", ossFileName + imgFile).getObjectSummaries();
            fileLength = ossHouseImgList.size();
            if (fileLength != 0) {
                OSSObjectSummary ossObjectSummary = ossHouseImgList.get(fileLength - 1);
                String reg = "\\d+";
                String[] split = ossObjectSummary.getKey().split("/");
                String s = split[2];
                Matcher matcher = Pattern.compile(reg).matcher(s);
                if (matcher.find()) {
                    // 将匹配当前正则表达式的字符串即文件名称进行赋值
                    fileLength = new Integer(matcher.group()) + 1;
                }
            }
            // 文件重命名：
            String ofn = file.getOriginalFilename();
            String ext = "." + ofn.split("\\.")[1]; // a.png => .png
            String imgName = "img_" + fileLength + ext; // img_0.png
            try {
                ossClient.putObject(bucketName, ossFileName + imgFile + "/" + imgName, file.getInputStream());
            } catch (IOException e) {
                return R.error("服务器开小差了！请重试！");
            }
        }
        ossClient.shutdown();
        return R.ok("图片上传成功！");
    }

    @Override
    public R removePicture(String fileName) {
        if (fileName == null) {
            return R.error("删除失败！文件错误！");
        }
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, fileName);
        ossClient.shutdown();
        return R.ok("删除成功！");
    }

    @Override
    public R updateHouseById(House house) {
        int i = mapper.updateById(house);
        if (i == 1) {
            return R.ok("更新成功！");
        }
        return R.error("更新失败！");
    }

    @Override
    public R createHouse(String token, House house) {
        Jws<Claims> info = JwtUtil.getTokenAdminInfo(token);
        if (info == null) {
            info = JwtUtil.getTokenUserInfo(token);
            if (info == null) {
                return R.error("用户信息错误！请重新登陆！");
            }
        }
        String subject = info.getBody().getSubject();
        if ("Admin-Login".equals(subject)) {
            house.setAdminId(JwtUtil.verifyToken(token));
        } else if ("User-Login".equals(subject)) {
            house.setSalerId(JwtUtil.verifyUserToken(token));
        }
        long v = (long) (Math.random() * (99999 - 10000) + 10000);
        long l = System.currentTimeMillis();
        String id = String.valueOf(l) + String.valueOf(v);
        house.setId(id);
        String imgFile = System.currentTimeMillis() + "_" + house.getId();
        house.setImgFile(imgFile);
        house.setCreateTime(TimeUtil.getNowTime());
        house.setHouseStatus(1);
        int i = mapper.insert(house);
        if (i == 1) {
            return R.ok("新增成功！", house.getId());
        }
        return R.error("新增失败！请重试！");
    }

    @Override
    public R getHouseSale(String token, String id) {
        Integer adminId = JwtUtil.verifyToken(token);
        if (adminId < 0) {
            return R.error("token 错误！请重新登录！");
        }
        House house = mapper.selectById(id);
        if (house == null) {
            return R.error("房源错误！");
        }
        house.setAdminId(adminId);
        int i = mapper.updateById(house);
        if (i == 1) {
            return R.ok("获取代理成功！");
        }
        return R.error("获取代理失败！");
    }

    @Override
    public R getNewHouse(Integer i) {
        QueryWrapper<House> houseQueryWrapper = new QueryWrapper<>();
        houseQueryWrapper.orderByDesc("create_time").last("limit " + i).eq("house_status", 1);
        List<House> houses = mapper.selectList(houseQueryWrapper);
        if (houses == null) {
            return R.error("服务器开小差了！");
        }
        for (House house : houses) {
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            List<OSSObjectSummary> houseImgList = ossClient.listObjects(bucketName, ossFileName + house.getImgFile()).getObjectSummaries();
            String[] imgS = new String[houseImgList.size()];
            for (int j = 0; j < imgS.length; j++) {
                imgS[j] = houseImgList.get(j).getKey();
            }
            house.setImgFileNames(imgS);
            ossClient.shutdown();
        }
        return R.ok(houses);
    }

    @Override
    public R getMyHouse(String token) {
        Integer id = JwtUtil.verifyUserToken(token);
        if (id > 0) {
            QueryWrapper<House> houseQueryWrapper = new QueryWrapper<>();
            houseQueryWrapper.eq("saler_id", id).eq("house_status", 1);
            List<House> houses = mapper.selectList(houseQueryWrapper);
            for (House house : houses) {
                OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
                List<OSSObjectSummary> houseImgList = ossClient.listObjects(bucketName, ossFileName + house.getImgFile()).getObjectSummaries();
                String[] imgS = new String[houseImgList.size()];
                for (int j = 0; j < imgS.length; j++) {
                    imgS[j] = houseImgList.get(j).getKey();
                }
                house.setImgFileNames(imgS);
                ossClient.shutdown();
            }
            return R.ok(houses);
        }
        return R.error();
    }

    @Override
    public R getHouseByPageAsFilter(Integer currentPage, Integer pageSize, String zone, String price, String area) {
        QueryWrapper<House> wrapper = new QueryWrapper<>();
        wrapper.eq("house_status", 1);
        if (!"0".equals(zone)) {
            wrapper.eq("zone_id", zone);
        }
        if (!"0".equals(price)) {
            String reg = "\\d+";
            Integer min = 10000;
            Integer max = 10000;
            if (price.matches("G\\d+L\\d+")) {
                Pattern p = Pattern.compile(reg);
                Matcher m = p.matcher(price);
                while (m.find()) {
                    if (max.equals(min)) {
                        min *= Integer.parseInt(m.group());
                    } else {
                        max *= Integer.parseInt(m.group());
                    }
                }
                wrapper.between("(price*area)", min, max);
            } else if (price.startsWith("G")) {
                Pattern p = Pattern.compile(reg);
                Matcher m = p.matcher(price);
                m.find();
                min *= Integer.parseInt(m.group());
                wrapper.ge("(price*area)", min);
            } else if (price.startsWith("L")) {
                Pattern p = Pattern.compile(reg);
                Matcher m = p.matcher(price);
                m.find();
                max *= Integer.parseInt(m.group());
                wrapper.le("(price*area)", max);
            }
        }
        if (!"0".equals(area)) {
            String reg = "\\d+";
            Integer min = 0;
            Integer max = 0;
            if (area.matches("G\\d+L\\d+")) {
                Pattern p = Pattern.compile(reg);
                Matcher m = p.matcher(area);
                while (m.find()) {
                    if (max.equals(min)) {
                        min = Integer.parseInt(m.group());
                    } else {
                        max = Integer.parseInt(m.group());
                    }
                }
                wrapper.between("area", min, max);
            } else if (area.startsWith("G")) {
                Pattern p = Pattern.compile(reg);
                Matcher m = p.matcher(area);
                m.find();
                min = Integer.parseInt(m.group());
                wrapper.ge("area", min);
            } else if (area.startsWith("L")) {
                Pattern p = Pattern.compile(reg);
                Matcher m = p.matcher(area);
                m.find();
                max = Integer.parseInt(m.group());
                wrapper.le("area", max);
            }
        }
        Page<House> page = new Page<>(currentPage, pageSize);
        page = mapper.selectPage(page, wrapper);
        if (page.getRecords().isEmpty()) {
            return R.error("找不到相应的房源，请重新选择筛选条件！");
        } else {
            for (House house : page.getRecords()) {
                OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
                List<OSSObjectSummary> houseImgList = ossClient.listObjects(bucketName, ossFileName + house.getImgFile()).getObjectSummaries();
                String[] imgS = new String[houseImgList.size()];
                for (int j = 0; j < imgS.length; j++) {
                    imgS[j] = houseImgList.get(j).getKey();
                }
                house.setImgFileNames(imgS);
                ossClient.shutdown();
            }
        }
        PageResult<House> data = new PageResult<>(page.getTotal(), page.getRecords());
        return R.ok(data);
    }

    @Override
    public R getVillage() {
        QueryWrapper<House> houseQueryWrapper = new QueryWrapper<>();
        houseQueryWrapper.select("village");
        List<House> list = mapper.selectList(houseQueryWrapper);
        HashSet<String> villages = new HashSet<>();
        list.forEach(house -> villages.add(house.getVillage()));
        return R.ok(villages);
    }

    @Override
    public R searchHouseByVillage(String village) {
        QueryWrapper<House> houseQueryWrapper = new QueryWrapper<>();
        houseQueryWrapper.like("village", village).eq("house_status", 1);
        List<House> houses = mapper.selectList(houseQueryWrapper);
        for (House house : houses) {
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            List<OSSObjectSummary> houseImgList = ossClient.listObjects(bucketName, ossFileName + house.getImgFile()).getObjectSummaries();
            String[] imgS = new String[houseImgList.size()];
            for (int j = 0; j < imgS.length; j++) {
                imgS[j] = houseImgList.get(j).getKey();
            }
            house.setImgFileNames(imgS);
            ossClient.shutdown();
        }
        return R.ok(houses);
    }

    @Override
    public R testUpload(MultipartFile[] files) {
        System.out.println(files);
//        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
//        List<OSSObjectSummary> ossHouseImgList = ossClient.listObjects("home-y", ossFileName + "123").getObjectSummaries();
//        System.out.println("ossHouseImgList.size:"+ossHouseImgList.size());
//        ossClient.shutdown();
        return R.ok("上传成功");
    }

    @Override
    public R deleteHouse(House house) {
        QueryWrapper<House> houseQueryWrapper = new QueryWrapper<>();
        houseQueryWrapper.eq("id", house.getId());
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("h_id", house.getId());
        int delete = mapper.delete(houseQueryWrapper);
        if (delete == 1) {
            orderMapper.delete(orderQueryWrapper);
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            for (String imgFileName : house.getImgFileNames()) {
                ossClient.deleteObject(bucketName, imgFileName);
            }
            ossClient.shutdown();
            return R.ok("下架成功");
        }
        return R.error("下架失败");
    }


}
